package com.microframework.boot.system.controller;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jfinal.kit.StrKit;
import com.microframework.base.core.util.SecurityUtils;
import com.microframework.base.core.util.UuidUtil;
import com.microframework.base.web.page.PageQuery;
import com.microframework.base.web.resp.R;
import com.microframework.boot.system.model.domain.Dict;
import com.microframework.boot.system.model.domain.DictItem;
import com.microframework.boot.system.service.IDictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/**
 * 字典管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/sys/dict")
@Tag(name = "字典管理", description = "字典管理相关接口")
public class DictController {

    @Autowired
    private IDictService dictService;
    
    
    @PostMapping("/load/all")
    @Operation(summary = "一次性加载树型数据", description = "一次性加载树型数据")
    public R<List<Dict>> loadAll(@RequestBody PageQuery<Dict> pageQuery) {
        return R.ok(dictService.loadAll(pageQuery));
    }
    
    @PostMapping("/load/lazy")
    @Operation(summary = "懒加载树型数据", description = "懒加载树型数据")
    public R<List<Dict>> loadLazy(@RequestBody PageQuery<Dict> pageQuery) {
        return R.ok(dictService.loadLazy(pageQuery));
    }
    
	@Operation(summary = "保存字典")
	@Parameters({ @Parameter(name = "dict", description = "字典", required = true) })
	@PostMapping("/save")
	public R<Dict> save(HttpServletRequest request, @RequestBody Dict dict) {
		try {
			if (StrKit.notBlank(dict.getId())) {
				Dict checkDict=Dict.dao.findFirst("select id from "+Dict.TABLE_NAME+" where code=? and id!=?",dict.getCode(),dict.getId());
				if(checkDict!=null) {
					return R.fail("字典标识重复.");
				}
				dict.setModifyTime(new Date(System.currentTimeMillis()));
				dict.setModifyUserId(SecurityUtils.getUserId());
				if (dict.update()) {
					return R.ok(dict);
				} else {
					return R.fail("更新失败.");
				}
			} else {
				Dict checkDict=Dict.dao.findFirst("select id from "+Dict.TABLE_NAME+" where code=? ",dict.getCode());
				if(checkDict!=null) {
					return R.fail("字典标识重复.");
				}
				dict.setId(UuidUtil.getUUID());
				dict.setCreateTime(new Date(System.currentTimeMillis()));
				dict.setCreateUserId(SecurityUtils.getUserId());
				if (dict.save()) {
					return R.ok(dict);
				} else {
					return R.fail("保存失败.");
				}
			}
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}
	
	@Operation(summary = "删除字典")
	@Parameters({ @Parameter(name = "id", description = "字典id", required = true) })
	@DeleteMapping("/detain/{id}")
	public R<String> deleteById(@PathVariable("id") String id) {
		try {
			Dict role=new Dict();
			role.setId(id);
			role.setIsDel("1");
			if(role.update()) {
				return R.ok("删除成功.");
			}else {
				return R.fail("删除失败.");
			}
		}catch (Exception e) {
			log.error("删除异常:{}",e.getMessage());
			return R.fail(e.getMessage());
		}
	}
	
    @PostMapping("/item/pages")
    @Operation(summary = "分页查询字典项列表", description = "分页查询字典项数据")
    public R<List<DictItem>> getItemPages(@RequestBody PageQuery<DictItem> pageQuery) {
        return R.ok(dictService.getItemPages(pageQuery));
    }
    
    
    @Operation(summary = "保存字典项")
	@Parameters({ @Parameter(name = "item", description = "字典项", required = true) })
	@PostMapping("/item/save")
	public R<DictItem> save(HttpServletRequest request, @RequestBody DictItem item) {
		return dictService.save( item);
	}
    
	@Operation(summary = "删除字典项")
	@Parameters({ @Parameter(name = "id", description = "字典项id", required = true) })
	@DeleteMapping("/item/detain/{id}")
	public R<String> deleteItemById(@PathVariable("id") String id) {
		return dictService.deleteItem( id);
	}
	
	@Operation(summary = "获取下拉框典项")
	@Parameters({ @Parameter(name = "code", description = "字典标识", required = true) })
	@GetMapping("/options/{code}")
	public R<List<DictItem>> getSelectOptions(@PathVariable("code") String code) {
		try {
			List<DictItem> list=DictItem.dao.find("select id,cn_label,en_label,value,status from "+DictItem.TABLE_NAME+" where is_del=0  and dict_id in (select id from "+Dict.TABLE_NAME+" where code=?) order by sort asc",code);
			return R.ok(list);
		}catch (Exception e) {
			log.error("获取下拉框典项异常:{}",e.getMessage());
			return R.fail(e.getMessage());
		}
	}
	
	@Operation(summary = "获取全部映射内容")
	@GetMapping("/mappings")
	public R<Map<String, Map<String, DictItem>>> getAllMappings() {
	    try {
	        // 1. 获取所有字典的ID和CODE
	        List<Dict> dictList = Dict.dao.find("SELECT id, code FROM " + Dict.TABLE_NAME + " WHERE is_del = 0");
	        if (dictList.isEmpty()) {
	            return R.ok(new HashMap<>());
	        }

	        // 2. 批量收集字典ID用于IN查询
	        List<Object> dictIds = new ArrayList<>(dictList.size());
	        Map<Object, String> dictIdToCodeMap = new HashMap<>(dictList.size());
	        for (Dict dict : dictList) {
	            dictIds.add(dict.getId());
	            dictIdToCodeMap.put(dict.getId(), dict.getCode());
	        }

	        // 3. 使用预编译SQL解决IN查询参数问题
	        StringBuilder sqlBuilder = new StringBuilder();
	        sqlBuilder.append("SELECT * FROM ")
	                  .append(DictItem.TABLE_NAME)
	                  .append(" WHERE is_del = 0 AND dict_id IN (");
	        
	        // 动态生成占位符 (?,?,...)
	        StringJoiner placeholders = new StringJoiner(",");
	        for (int i = 0; i < dictIds.size(); i++) {
	            placeholders.add("?");
	        }
	        sqlBuilder.append(placeholders)
	                  .append(") ORDER BY dict_id, sort ASC");

	        // 4. 执行带参数的查询
	        List<DictItem> allItems = DictItem.dao.find(sqlBuilder.toString(), dictIds.toArray());

	        // 5. 按dict_id分组字典项
	        Map<Object, List<DictItem>> groupedItems = allItems.stream()
	                .collect(Collectors.groupingBy(DictItem::getDictId));

	        // 6. 构建最终结果
	        Map<String, Map<String, DictItem>> resultMap = new HashMap<>();
	        for (Dict dict : dictList) {
	            List<DictItem> items = groupedItems.get(dict.getId());
	            if (items != null && !items.isEmpty()) {
	                Map<String, DictItem> itemMap = items.stream()
	                        .collect(Collectors.toMap(
	                            DictItem::getValue, 
	                            item -> item,
	                            (existing, replacement) -> existing  // 处理重复键
	                        ));
	                resultMap.put(dict.getCode(), itemMap);
	            }
	        }

	        return R.ok(resultMap);
	    } catch (Exception e) {
	        log.error("获取全部映射内容异常: {}", e.getMessage());
	        return R.fail(e.getMessage());
	    }
	}
	
	
} 